from flask import render_template,redirect,url_for,session, flash, request, jsonify
from flask_login import login_required, current_user
#from flaskext.uploads import UploadSet, IMAGES

from werkzeug.utils import secure_filename

from controller import app
from lib.form import Form
from model.item import Item, ItemDao
from model.picture import Picture
from service.item_picture import ItemPictureService
from model.picture import PictureDao


from model.company import CompanyDao
from service.item import ItemValidator, ItemService, ItemForm

from core import user_permission

from bson.objectid import ObjectId
from bson.dbref import DBRef
import json

IMAGES = tuple('jpg jpe jpeg png gif svg bmp'.split())


@app.errorhandler(403)
def page_not_found(e):
    session['redirected_from'] = request.url
    return redirect(url_for('login'))

            
@app.route('/validate_item')
@app.route('/validate_item', methods=['GET','POST'])
@login_required
def validate_item():
    values = {}
    if request.values['page'] == '0':
        for key in request.values:
            values[key] = request.values[key]
    
    v = ItemValidator()
    ret = v.validate(values)
    return jsonify(errors=ret)


@app.route('/submit_item', methods=['GET','POST'])
@login_required
def submit_item():
    form = ItemForm()
    if form.is_submitted():
        if form.has_error():
            session['errors_json'] = json.dumps(form.errors)
            return redirect(url_for('display_items'))#errors_json=json.dumps(form.errors)))
        else:
            company_name = request.values.get('company_name')
            fname = request.values.get('pic_fname')
            
            service = ItemService()
            item_id = service.submit_item(form.inputs)
            
            item_pic_serv = ItemPictureService(company_name, item_id)
            fpath = item_pic_serv.get_path(fname)
            item_pic_serv.submit_item_picture(fpath, item_id)
                  
            return redirect(url_for('display_items', company_name=form.raw_inputs['company_name']))
    return redirect(url_for('display_items', company_name=form.raw_inputs['company_name']))


@user_permission.require(http_exception=403)        
@app.route('/manage_items/<string:company_name>')
@app.route('/manage_items/<string:company_name>', methods=['GET','POST'])
@login_required
def manage_items(company_name):
    #form = ItemForm()
    #item_dao = ItemDao()
    return redirect(url_for('display_items', company_name=company_name))

@app.route('/display_items')
@login_required
def display_items():
    #return render_template("add_item-v1.html", items=None)
    # Check if there is only one company
    company_name = request.args['company_name']
    company_dao = CompanyDao()
    #companies = company_dao.get_companies_by_user(current_user)
    company = company_dao.find_one({'name':company_name})
    user = {'name':current_user.username, 'role':int(current_user.role)}
    
    item_serv = ItemService()
    items = item_serv.get_items_by_company(company)
    
    return render_template("manage_items.html", items=items, pictures=None, errors_json=[], company_name=company.name, user=user)


@app.route("/get_items")
@app.route("/get_items", methods=['GET','POST'])
@login_required
def get_items():
    """ This is an Ajax handler
    """
    company_name = request.values['company_name']
    company_dao = CompanyDao()
    company = company_dao.find_one({'name':company_name})
    item_serv = ItemService()
    items = item_serv.get_items_by_company(company)
    
    return jsonify(items=json.dumps(items))



@app.route("/preload_image/<string:company_name>")
@app.route("/preload_image/<string:company_name>", methods=['GET','POST'])
@login_required
def preload_image(company_name):
    """ This is an Ajax upload
    """
    _id = request.values.get('oid')
    file_data = request.values.get('fdata').split(':')[1]
    file_name = request.values.get('fname')
    
    if _id == '0' or _id=='':
        #item_id = ObjectId(_id)
        #item_dao = ItemDao()
        item_id = ObjectId()
        _id = str(item_id)
    item_picture = ItemPictureService(company_name, _id)
    folder = item_picture.get_folder()      
    item_picture.ajax_upload(file_data, file_name, folder)
    
    _fpath = r'../' + folder + r'/' + file_name
    return jsonify(fname=file_name,fpath=_fpath, oid=str(_id))

    '''
    _id = request.values.get('oid')
    if _id != '0':
        object_id = ObjectId(_id)
        ad_dao = AdvertisementDao()
        ItemDaoClass = ad_dao.items[category_name][1]
        
        item_dao = ItemDaoClass()
        
        # Should never jump to the following line
        if item_dao.find_one({'_id':object_id}) is not None:
            _id = ObjectId()
    else:
        _id = ObjectId()
        session_dao = SessionDao()
        session_dao.save({'user_id':current_user.id,
                          'item_id':_id})
    
    picture_service = PictureService(current_user.username, category_name, _id)
    picture_service.create_picture_folders()
    
    file_data = request.values.get('fdata').split(':')[1]
    file_name = request.values.get('fname')
    
    fservice = FileService(file_data)
    fservice.save(file_name, picture_service.path)
    _fpath = r'../' + picture_service.path + r'/' + file_name
    return jsonify(fpath=_fpath, oid=str(_id))
    #return render_template("real_estates.html", infos=infos)
    '''   
@app.route('/edit_item')
@login_required
def edit_item():
    item_dao = ItemDao()
    _items = item_dao.filter_by(user_id=current_user.get_id())
    return render_template("items.html", items=_items)
    
@app.route("/delete_items", methods=["GET", "POST"])
@login_required
def delete_items():
    item_dao = ItemDao()
    '''
    form = ItemsForm()
    ids = form.request.form.getlist('selected')
    for _id in ids:
        item = item_dao.filter_first(id=int(_id))
        picture_service = PictureService(item)
        picture_service.delete_pictures()
        
        item_dao.remove_item(item)
    '''    
    return render_template("manage_items.html", items=item_dao.filter_by(user_id=current_user.id))            


